package com.lanou.renrenxin.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.lanou.renrenxin.R;
import com.lanou.renrenxin.adapter.TabAdapter;
import com.lanou.renrenxin.base.BaseActivity;
import com.lanou.renrenxin.base.BaseApplication;
import com.lanou.renrenxin.custommodule.NoScrollViewPager;
import com.lanou.renrenxin.fragment.ChatFragment;
import com.lanou.renrenxin.fragment.FriendFragment;
import com.lanou.renrenxin.fragment.PersonalFragment;
import com.lanou.renrenxin.fragment.SetFragment;
import com.lanou.renrenxin.singleton.RenrenxinSingleton;
import com.lanou.renrenxin.tools.LogUtils;

import java.util.ArrayList;

public class MainActivity extends BaseActivity {
    private ArrayList<Fragment> fragments;
    private NoScrollViewPager viewPager;
    private RadioGroup tabRadioGroup;
    private RadioButton chatRadioBtn;
    private TabAdapter tabAdapter;
    private Handler handler;
    private String mUserName = new String();
    private String s;
    private NewMessageBroadcastReceiver msgReceiver;
    private Button btnAdd,btnSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findId();
        loadData();
        //设置环信好友体系
        EMChatManager.getInstance().getChatOptions().setUseRoster(true);

        mUserName = getIntent().getStringExtra("LOGIN_USER_NAME");
        LogUtils.e("ççççç", mUserName);
        Toast.makeText(this, "登陆成功", Toast.LENGTH_SHORT).show();
        //只有注册了广播才能接收到新消息，目前离线消息，在线消息都是走接收消息的广播（离线消息目前无法监听，在登录以后，接收消息广播会执行一次拿到所有的离线消息）
        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(3);
        registerReceiver(msgReceiver, intentFilter);

        findId();

        for (int i = 0; i < 1; i++) {
            chat(i);
        }
        loadData();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(msgReceiver);
    }


    private void findId() {
        viewPager = (NoScrollViewPager) findViewById(R.id.viewPager_activity_main);
        tabRadioGroup = (RadioGroup) findViewById(R.id.radioGroup_activity_main_tab);
        chatRadioBtn = (RadioButton) findViewById(R.id.radioBtn_activity_main_chat);
        btnAdd = (Button) findViewById(R.id.btnAdd);
        btnSearch = (Button) findViewById(R.id.btnSearch);
    }

    private void loadData() {
        fragments = new ArrayList<>();

        ChatFragment chatFragment = new ChatFragment();
        FriendFragment friendFragment =  new FriendFragment();
        fragments.add(chatFragment);
        fragments.add(friendFragment);
        fragments.add(new PersonalFragment());
        fragments.add(new SetFragment());
        Bundle bundle = new Bundle();
        bundle.putString("USER_NAME_MAIN", mUserName);
        bundle.putString("TO_USERNAME", s);
        chatFragment.setArguments(bundle);
        friendFragment.setArguments(bundle);
        tabAdapter = new TabAdapter(getSupportFragmentManager(), fragments, BaseApplication.getContext());
        viewPager.setAdapter(tabAdapter);
        viewPager.setCurrentItem(0, true);
        chatRadioBtn.setChecked(true);
        tabRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radioBtn_activity_main_chat:
                        viewPager.setCurrentItem(0, false);
                        break;
                    case R.id.radioBtn_activity_main_friend:
                        viewPager.setCurrentItem(1, false);
                        break;
                    case R.id.radioBtn_activity_main_personal:
                        viewPager.setCurrentItem(2, false);
                        break;
                    case R.id.radioBtn_activity_main_set:
                        viewPager.setCurrentItem(3, false);
                        break;
                }
            }
        });

        btnAdd.setVisibility(View.VISIBLE);
        btnSearch.setVisibility(View.VISIBLE);
    }

    private void chat(int i) {
        s = "00002";
        //获取到与聊天人的会话对象。参数username为聊天人的userid或者groupid，后文中的username皆是如此

        if (mUserName.equals("00002")) {
            s = "00001";
        }

        EMConversation conversation = EMChatManager.getInstance().getConversation(s);

//创建一条文本消息
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
//如果是群聊，设置chattype,默认是单聊
//        message.setChatType(EMMessage.ChatType.GroupChat);
//设置消息body
        TextMessageBody txtBody = new TextMessageBody("Hello World" + i);
        message.addBody(txtBody);
//设置接收人
        message.setReceipt(s);
//把消息加入到此会话对象中
        conversation.addMessage(message);
//发送消息
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
                RenrenxinSingleton.getInstence().saveChatList(mUserName, s, "Hello World", "2016年03月04日21:34", 1, 0,"TXT");
                LogUtils.e("******", "发送成功");
            }

            @Override
            public void onError(int i, String s) {
                RenrenxinSingleton.getInstence().saveChatList(mUserName, s, "Hello World", "2016年03月04日21:34", 1, 1,"TXT");
                LogUtils.e("******", "发送失败");
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }


    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 注销广播
            abortBroadcast();

            // 消息id（每条消息都会生成唯一的一个id，目前是SDK生成）
            String msgId = intent.getStringExtra("msgid");
            //发送方
            String username = intent.getStringExtra("from");
            // 收到这个广播的时候，message已经在db和内存里了，可以通过id获取mesage对象
            EMMessage message = EMChatManager.getInstance().getMessage(msgId);
            EMConversation conversation = EMChatManager.getInstance().getConversation(username);
            Toast.makeText(context, ((TextMessageBody) message.getBody()).getMessage(), Toast.LENGTH_SHORT).show();
            // 如果是群聊消息，获取到group id
            if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                username = message.getTo();
            }
            if (!username.equals(username)) {
                // 消息不是发给当前会话，return
                return;
            }
        }
    }

}



